package com.mjlf.mqzook.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mjlf.mqzook.entity.RegistryServer;
import com.mjlf.mqzook.inter.RegistryFacotry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName ServerRegistryController
 * @Author mjlft
 * @Date 2020/2/18 11:08
 * @Version 1.0
 * @Description 服务注册controller
 */
@RestController
public class ServerRegistryController implements RegistryFacotry {

    Logger logger = LoggerFactory.getLogger(ServerRegistryController.class);

    @Override
    @PostMapping("/registry")
    public JSONObject registry(@RequestBody RegistryServer registryServer){
        JSONObject jsonObject = new JSONObject();
        registryServer.setUpdateTime(System.currentTimeMillis());
        Set<RegistryServer> registryServers = RegistryFacotry.servers.get(registryServer.getName());
        if(registryServers == null){
            registryServers = new HashSet<>(16);
            registryServers.add(registryServer);
        }else {
            registryServers.remove(registryServer);
            registryServers.add(registryServer);
        }
        RegistryFacotry.servers.put(registryServer.getName(), registryServers);
        logger.info("更新服务{}:{}", registryServer.getHost(), registryServer.getPort());
        jsonObject.put("code", 200);
        return jsonObject;
    }

    @Override
    @GetMapping("/getServers")
    public JSONObject getServers() {
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(RegistryFacotry.servers));
        JSONObject result = new JSONObject();
        result.put("code", 200);
        result.put("data", jsonObject);
        return result;
    }
}
